import { Ref, onMounted, ref } from "vue";
import MarkdownIt from "markdown-it";
import { ArticleDetail } from "@/types/article";
import { queryArticleDetail } from "@/api/article.api";
import { useRoute } from "vue-router";
import hljs from "highlight.js";
// import MarkdownItToc from "markdown-it-toc";
export const useArticleRender = (): {
  article: Ref<ArticleDetail>;
  articleHtml: Ref<string>;
  articleToc: Ref<string>;
} => {
  const route = useRoute();
  const articleToc = ref("");
  const article = ref(new ArticleDetail());
  const articleHtml = ref("");
  const getArticleInfo = async (id: string) => {
    const res = await queryArticleDetail(id);
    if (res.code === 200) {
      article.value = res.data || new ArticleDetail();
      renderMd();
    }
  };
  const renderMd = () => {
    const md = new MarkdownIt({
      html: true,
      linkify: true,
      typographer: true,
      highlight: function (str: string, lang: string) {
        const language = hljs.getLanguage(lang) ? lang : "plaintext";
        // 返回分割后的数组
        // 根据换行符或回车分割成字符串数组
        const getLines = (text: string) => {
          if (text.length === 0) return [];
          return text.split(/\r\n|\r|\n/g);
        };
        const textHtml = hljs.highlight(str, { language }).value;
        const lines = getLines(textHtml);

        // 自定义代码块的标签节点
        let html = "";
        for (let i = 0, l = lines.length; i < l - 1; i++) {
          const text = lines[i].length > 0 ? lines[i] : " ";
          html += `<tr>
         <td class="blob-num" data-line-number="${i + 1}"></td>
         <td class="blob-code blob-code-inner">${text}</td>
       </tr>`;
        }
        return `<pre class="hljs"><code><table class="highlight" data-lang="${language}">${html}</table></code></pre>`;
        // return `<table class="highlight" data-lang="${language}">${html}</table>`;
      },
      langPrefix: "hljs language-",
      breaks: false,
      xhtml: false,
    });
    // md.use(MarkdownItToc, []);
    const mdResult = md.render(article.value.content);

    articleHtml.value = mdResult;
    articleToc.value = md.toc;
  };
  onMounted(() => {
    const articleId = route.query.id as string;
    articleId && getArticleInfo(articleId);
  });
  return {
    article,
    articleHtml,
    articleToc,
  };
};
